package com.sc.everyonerentboot.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sc.everyonerentboot.mapper.UsersMapper;
import com.sc.everyonerentboot.pojo.Users;
import com.sc.everyonerentboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UsersMapper mapper;
    @Value("${avatar.path}")
    private String UpDir;
    @Override
    public int register(Users u) {
        return mapper.insertSelective(u);
    }

    @Override
    public int delAll(Integer ids[]) {
        int count=0;
        for (Integer id:ids){
            count=count+mapper.deleteByPrimaryKey(id);
        }
        return count;
    }

    @Override
    public int del(Integer id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Users login(Users u) {
        return mapper.selectLogin(u);
    }

    @Override
    public int update(Users u) {
        return mapper.updateByPrimaryKeySelective(u);
    }

    @Override
    public PageInfo<Users> showAll(Integer pageNum, Integer pageSize,Users u) {
        PageHelper.startPage(pageNum,pageSize);
        return new PageInfo<Users>(mapper.selectAll(u));
    }

    @Override
    public String avatar(MultipartFile file) {
        Path filePath;
        String fileName = null;
        try{
            // 生成唯一文件名
            fileName = UUID.randomUUID().toString() + ".jpg";
            // 获取 resources 目录下的 avatars 文件夹路径
            Path avatarDir = Paths.get("EveryoneRentBoot","src", "main", "resources", "avatars");
            // 如果目录不存在，则创建目录
            if (!Files.exists(avatarDir)) {
                Files.createDirectories(avatarDir);
            }
            // 将文件路径拼接为 avatarDir + fileName
            filePath = avatarDir.resolve(fileName);
            Files.write(filePath,file.getBytes());
        }catch (IOException e){
            e.printStackTrace();
        }
        return fileName;
    }
}
